<?php

	session_start();
	require_once('../inc/fnc.php');
	
	if(isset($_GET['msgid'])){
		$query = "SELECT `senderid`, `receiverid` FROM `msgtable` where msgid = {$_GET['msgid']} LIMIT 1";
		$result = mysql_query($query);
		$row = mysql_fetch_array($result);
		
		if($row['receiverid'] == $_SESSION['userId']){
			$receiverid = $row['senderid'];
		} else if($row['senderid'] == $_SESSION['userId']){
		} else if($row['senderid'] == $_SESSION['userId']){
			$receiverid = $row['receiverid'];
		}
	} else {
		$receiverid = $_GET['to'];
	}

	$msg = mysql_prep($_GET['msg']);
	
	$msgId = sendmsg($_SESSION['userId'], $receiverid, $msg);
	
	if(!$msgId){
		//return false;
		$error['status'] = false;
	} else {
		//return true;
		if(sendMsgNotification($receiverid, $_GET['msg'], $msgId)){
			$error['status'] = true;
			$error['msgid'] = $msgId;
			
			if(isset($_GET['msgid'])){
				$query = "SELECT * FROM  `msgtable` where `sendershow` = 'N' and `msgid` = '{$msgId}' ORDER BY `crtdtime` DESC LIMIT 1";
				$result = mysql_query($query, $connection);
				
				
				$row = mysql_fetch_array($result);
				$queryUser = "SELECT * FROM `users` WHERE `userid` = {$row['senderid']} and `delete flag` = 'N' LIMIT 1";
				$result1 = mysql_query($queryUser, $connection);
				if($result1){ while($rows = mysql_fetch_array($result1)) { $user = $rows['username']; } }
			
				$avatarPath = userimage($row['senderid'],'small');
				$showTime = timeago($row['crtdtime']);
				$username = getUsername($row['senderid']);
				
				$error['markup'] = "<li class='eachLine box' style='border-top: 1px solid #CCC;'> 
										<div class='elMta left'>
											<input id='msgdel{$row['id']}' value='x' data-muid='{$row['id']}' class='msg-del' name='del' type='button'/>
										</div> 
										<div class='el left' style='width: 390px; margin-right: 10px;'>
											 <p>{$row['msg']}</p>
											<div class='elLineMta'>
												<div class='lineMtaItemOne'><span class='timeagoIcon'></span><abbr class='timeago' title='{$showTime}'>{$showTime}</abbr></div>
											</div>
										</div> 
										<div class='elInfo left'> 
											<a href='index.php?page=" . strtolower($username) . "' class='avatar'>
												<img src='{$avatarPath}' width='40' height='40' />
											</a> 
											<a href='index.php?page=" . strtolower($username) . "' class='username' style='margin-left: 5px;'>
												<span class='left'>{$username}</span>
											</a>
										</div> 										
										<div class='clear'></div> 
									</li>";
				
				
			}
		} else {
			$error['status'] = false;
		}
	}

	echo json_encode($error);


?>